package com.ymatou.apigateway.testcase;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.shop2cn.iapi.shenqisettlement.parameter.bean.AgentProductBean;
import com.shop2cn.iapi.sqoptrade.parameter.req.PlaceOrderReq;
import com.shop2cn.iapi.sqoptrade.parameter.vo.OrderItemVo;
import com.shop2cn.iapi.sqoptrade.resp.TradingServiceResp;
import com.ymatou.apigateway.parameter.AesUtil;
import com.ymatou.apigateway.parameter.OpenapiReq;
import com.ymatou.apigateway.parameter.SqProductExtInfo;
import com.ymatou.apigateway.parameter.SqPushSqOrderExtInfoReq;
import com.ymatou.apigateway.service.OpenapiService;
import com.ymatou.apigateway.service.SqPushSqOrderExtInfoCall;
import com.ymt.core.tool.FormatUtil;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.tag.P1;
import com.ymttest.business.service.shenqi.DGSQBuildProxyChainCallService;
import com.ymttest.business.service.shenqi.SqTradingCallService;
import com.ymttest.business.service.shenqi.SqTradingProductService;
import com.ymttest.business.service.shenqi.bean.PackageInfoByCatalogIdListResponse;
import com.ymttest.database.model.Application;
import com.ymttest.database.model.AuthCode;
import com.ymttest.database.sharding.db.ext.model.OrderDetailExtPo;
import com.ymttest.database.sharding.db.sharding.model.OrderDetailPo;
import com.ymttest.database.sharding.db.sharding.model.OrderDetailSubPo;
import com.ymttest.database.sharding.db.sqlwapper.OrderShardingWapper;
import com.ymttest.database.sharding.db.sqlwapper.OrderWapper;
import com.ymttest.database.sqlwapper.OpenApiWapper;
import com.ymttest.utils.DataUtil;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.TestDataManager;
import com.ymttest.utils.YMTDateUtil;

public class Ts_SqPushSqOrderExtInfo {

	private static OpenapiReq openapiReq;
	
	private static SqPushSqOrderExtInfoReq sqPushSqOrderExtInfoReq;
	private static SqPushSqOrderExtInfoCall sqPushSqOrderExtInfoCall;
	
	private static OpenApiWapper openApiWapper;
	private static OrderShardingWapper orderShardingWapper = new OrderShardingWapper();
	private static OrderWapper orderWapper = new OrderWapper();
	
	private static long autotest_goodsOwnerId = Long.valueOf(EnvSetup
			.getData("autotest_goodsOwnerId")); 

	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("openapi推送商品额外信息");
		openApiWapper = new OpenApiWapper();
	}

	@Before
	public void caseUp() {

		openapiReq = new OpenapiReq();
		
		sqPushSqOrderExtInfoReq = new SqPushSqOrderExtInfoReq();
		sqPushSqOrderExtInfoCall = new SqPushSqOrderExtInfoCall();
		
		openapiReq.setMethod("sq.orderextinfo.push");

	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(sqPushSqOrderExtInfoCall.getOpurl());
	}

	@After
	public void caseDown() {
		Logger.end();
	}
	
	public void verify(Long orderId) {
		
		orderShardingWapper.clearCache();
		
		List<OrderDetailPo> orderDetailList = orderShardingWapper.selectOrderDetailbyOrderId(orderId);
		
		for (OrderDetailPo orderDetailPo : orderDetailList) {
			
			Long orderDetailId = orderDetailPo.getOrderDetailId();
			
			OrderDetailExtPo orderDetailExtPo = orderWapper.selectOrderDetailExtByOrderId(orderDetailId);
			
			SqProductExtInfo sqProductExtInfo = sqPushSqOrderExtInfoReq
					.getProduct_ext_infos()
					.stream()
					.filter(info -> info.getOuter_sku_id().equalsIgnoreCase(
							orderDetailExtPo.getSku())).findAny().orElse(null);
			
			if (null != sqProductExtInfo) {
				
				Logger.verifyEquals(orderDetailPo.getGoodsSupplier(),
						sqProductExtInfo.getGoods_supplier(),
						"验证Goods_supplier");
				DataUtil.verifyDecimalEquals(orderDetailPo.getCustomsTaxFee(),
						sqProductExtInfo.getCustoms_tax_fee(),
						"验证Customs_tax_fee");
				DataUtil.verifyDecimalEquals(orderDetailPo.getCustomsTaxRate(),
						sqProductExtInfo.getCustoms_tax_rate(),
						"验证Customs_tax_rate");				
			}
			
			
			if (orderDetailPo.getSubProduct()) {
				
				List<OrderDetailSubPo> orderDetailSubPoList = orderShardingWapper.selectOrderDetailSubByDetailId(orderDetailId);
				
				for (OrderDetailSubPo orderDetailSubPo : orderDetailSubPoList) {
					
					sqProductExtInfo = sqPushSqOrderExtInfoReq
							.getProduct_ext_infos()
							.stream()
							.filter(info -> info.getOuter_sku_id().equalsIgnoreCase(
									orderDetailSubPo.getSku())).findAny().orElse(null);
					
					if (null != sqProductExtInfo) {
						
						Logger.verifyEquals(orderDetailSubPo.getGoodsSupplier(),
								sqProductExtInfo.getGoods_supplier(),
								"验证Goods_supplier");
						DataUtil.verifyDecimalEquals(orderDetailSubPo.getCustomsTaxFee(),
								sqProductExtInfo.getCustoms_tax_fee(),
								"验证Customs_tax_fee");
						DataUtil.verifyDecimalEquals(orderDetailSubPo.getCustomsTaxRate(),
								sqProductExtInfo.getCustoms_tax_rate(),
								"验证Customs_tax_rate");				
					}
				}
			}
		}
	}
	
	@SuppressWarnings("static-access")
	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_SqPushSqOrderExtInfo_001() {
		Logger.start(true, "openapi货头推送商品额外信息，推送成功");
		try {
			
//			AgentProductBean productBean = DGSQBuildProxyChainCallService
//					.createProxychain((int) autotest_goodsOwnerId, 0, false);
//
//			TradingServiceResp placeOrderResp = SqTradingCallService
//					.placeOrderWithMultiProsInOneOrder(productBean);
//			
//			Thread.sleep(5000);
//			
//			Long orderId = placeOrderResp.getOrderList().get(0).getOrderId();
//			Long sellerId = placeOrderResp.getOrderList().get(0).getSellerId();
			
			Long orderId = 14022300783L;
			Long sellerId = 502060981L;
			
			SqProductExtInfo sqProductExtInfo = new SqProductExtInfo();
			
			sqProductExtInfo.setOuter_sku_id("C052900");
			sqProductExtInfo.setCustoms_tax_fee(BigDecimal.TEN);
			sqProductExtInfo.setCustoms_tax_rate(new BigDecimal("0.2881"));
			sqProductExtInfo.setGoods_supplier("海鲲专供");

			sqPushSqOrderExtInfoReq.setOrder_id(orderId);
			sqPushSqOrderExtInfoReq.setProduct_ext_infos(Arrays.asList(sqProductExtInfo));

			Application application = openApiWapper
					.selectApplicationBySellerId(sellerId).get(0);

			String app_id = application.getApp_id();

			AuthCode authCode = openApiWapper.selectAuthCodeByAppId(app_id)
					.get(0);

			openapiReq.setApp_id(app_id);

			String app_secret = application.getApp_secret();

			openapiReq.setSign_method("MD5");
			openapiReq.setAuth_code(authCode.getAuth_code());
			openapiReq.setTimestamp(YMTDateUtil.getSysTime());
			openapiReq.setNonce_str(TestDataManager.getRandomNum(31));
			openapiReq.setBiz_content(new FormatUtil()
					.beanToGSONString(sqPushSqOrderExtInfoReq));
			String url = String
					.format("http://apigateway.shop2cn.com/apigateway/v1?app_id=%s&method=sq.orderextinfo.push",
							app_id);

			sqPushSqOrderExtInfoCall.setUrl(url);

			openapiReq.setSign(OpenapiService.generateMD5(openapiReq,
					AesUtil.decrypt(app_secret)));

			sqPushSqOrderExtInfoCall.setData(openapiReq);
			sqPushSqOrderExtInfoCall.callService();

			Logger.verifyEquals("0000", sqPushSqOrderExtInfoCall.getCode(), 
					"校验code");
			Logger.verifyEquals("操作成功", sqPushSqOrderExtInfoCall.getMsg(),
					"校验message");

			Logger.verifyNotNull(sqPushSqOrderExtInfoCall.getContent(),
					"校验content");
			
			this.verify(orderId);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@SuppressWarnings("static-access")
	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_SqPushSqOrderExtInfo_002() {
		Logger.start(true, "openapi货头推送组合商品额外信息，推送成功");
		try {
			
			PlaceOrderReq placeOrderReq = new PlaceOrderReq();
			
			AgentProductBean productBean1 = DGSQBuildProxyChainCallService
					.createComposeProductProxychain(
							(int) autotest_goodsOwnerId, false, false);
			
			PackageInfoByCatalogIdListResponse response = SqTradingProductService
					.getPackageInfoByCatalogIdList(
							productBean1.getGoodsOwnerId(),
							Arrays.asList(productBean1.getCatalogList().get(0)));
			
			String subSkuId = response.getProductPackageList().get(0)
					.getSubCatalogList().get(0).getSkuId();
			String subSkuId2 = response.getProductPackageList().get(0)
					.getSubCatalogList().get(1).getSkuId();

			placeOrderReq = SqTradingCallService
					.buildDGSQStandPlaceOrderReq(0, BigDecimal.ZERO, 20238699,
							productBean1, productBean1.getSellerId(), false);

			OrderItemVo orderItemVo1 = placeOrderReq.getOrderGroups().get(0)
					.getOrders().get(0).getOrderItems().get(0);

			orderItemVo1.setSubProduct(true);
			orderItemVo1.setProdTaxRate(new BigDecimal("0.17"));

			AgentProductBean productBean2 = DGSQBuildProxyChainCallService
					.createProxychain((int) autotest_goodsOwnerId, 0, false);

			OrderItemVo orderItemVo2 = SqTradingCallService
					.createOrderItemVo(productBean2.getRootProductId(),
							productBean2.getCatalogList().get(0));

			orderItemVo2.setSku(subSkuId);
			orderItemVo2.setProdTaxRate(new BigDecimal("0.12"));

			placeOrderReq.getOrderGroups().get(0).getOrders().get(0)
					.getOrderItems().add(orderItemVo2);
			
			TradingServiceResp placeOrderResp = SqTradingCallService.callPlaceOrderService(placeOrderReq);
			
			Thread.sleep(5000);
			
			Long orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			Long sellerId = productBean1.getGoodsOwnerId();
			
//			Long orderId = 13128878699L;
//			Long sellerId = 500002490L;
			
			SqProductExtInfo sqProductExtInfo = new SqProductExtInfo();
			
//			String subSkuId = "843410637";
			
			sqProductExtInfo.setOuter_sku_id(subSkuId);
			sqProductExtInfo.setCustoms_tax_fee(BigDecimal.TEN);
			sqProductExtInfo.setCustoms_tax_rate(new BigDecimal("0.3881"));
			sqProductExtInfo.setGoods_supplier("海鲲专供");
			
			SqProductExtInfo sqProductExtInfo2 = new SqProductExtInfo();
			
//			String subSkuId2 = "695663146";
			
			sqProductExtInfo2.setOuter_sku_id(subSkuId2);
			sqProductExtInfo2.setCustoms_tax_fee(BigDecimal.TEN);
			sqProductExtInfo2.setCustoms_tax_rate(new BigDecimal("0.1881"));
			sqProductExtInfo2.setGoods_supplier("海鲲专供2");

			sqPushSqOrderExtInfoReq.setOrder_id(orderId);
			sqPushSqOrderExtInfoReq.setProduct_ext_infos(Arrays.asList(sqProductExtInfo, sqProductExtInfo2));

			Application application = openApiWapper
					.selectApplicationBySellerId(sellerId).get(0);

			String app_id = application.getApp_id();

			AuthCode authCode = openApiWapper.selectAuthCodeByAppId(app_id)
					.get(0);

			openapiReq.setApp_id(app_id);

			String app_secret = application.getApp_secret();

			openapiReq.setSign_method("MD5");
			openapiReq.setAuth_code(authCode.getAuth_code());
			openapiReq.setTimestamp(YMTDateUtil.getSysTime());
			openapiReq.setNonce_str(TestDataManager.getRandomNum(31));
			openapiReq.setBiz_content(new FormatUtil()
					.beanToGSONString(sqPushSqOrderExtInfoReq));
			String url = String
					.format("http://apigateway.shop2cn.com/apigateway/v1?app_id=%s&method=sq.orderextinfo.push",
							app_id);

			sqPushSqOrderExtInfoCall.setUrl(url);

			openapiReq.setSign(OpenapiService.generateMD5(openapiReq,
					AesUtil.decrypt(app_secret)));

			sqPushSqOrderExtInfoCall.setData(openapiReq);
			sqPushSqOrderExtInfoCall.callService();

			Logger.verifyEquals("0000", sqPushSqOrderExtInfoCall.getCode(), 
					"校验code");
			Logger.verifyEquals("操作成功", sqPushSqOrderExtInfoCall.getMsg(),
					"校验message");

			Logger.verifyNotNull(sqPushSqOrderExtInfoCall.getContent(),
					"校验content");
			
			this.verify(orderId);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	public static void main(String[] args) {
		
		Ts_SqPushSqOrderExtInfo test = new Ts_SqPushSqOrderExtInfo();
//		test.Tc_sqgetorderlist_008();
		
		sqPushSqOrderExtInfoReq = new SqPushSqOrderExtInfoReq();
		
		SqProductExtInfo sqProductExtInfo = new SqProductExtInfo();
		
		sqProductExtInfo.setOuter_sku_id("sku111");
		sqProductExtInfo.setCustoms_tax_fee(BigDecimal.TEN);
		sqProductExtInfo.setCustoms_tax_rate(new BigDecimal("0.2881"));
		sqProductExtInfo.setGoods_supplier("海鲲专供");

		sqPushSqOrderExtInfoReq.setOrder_id(13133868699L);
		sqPushSqOrderExtInfoReq.setProduct_ext_infos(Arrays.asList(sqProductExtInfo));
		
		test.verify(13133868699L);
	}
}
